import "./reset.css";
import dayjs from "dayjs";
import roleForm from "../form/role.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import {
  usePublicHooks,
  formatHigherDeptOptions,
  customRolePermissionOptions
} from "@/utils/viewsPublic";
import { renderOption } from "@/utils/viewsRender";
import { addDialog } from "@/components/ReDialog";
import ReCropperPreview from "@/components/ReCropperPreview";
import type { RoleFormItemProps } from "../utils/types";
import { staffApi } from "@/api/organization/staff";
import { getDeptList } from "@/api/organization/department";
import { getRoleList } from "@/api/organization/role";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  watch,
  computed,
  reactive,
  onMounted,
  shallowRef
} from "vue";
import { hasAuth } from "@/router/utils";
import { useI18n } from "vue-i18n";
import { REGEXP_PWD } from "@/views/login/utils/rule";
import {
  cloneDeep,
  deviceDetection,
  hideTextAtIndex,
  isAllEmpty,
  isEmail,
  isPhone
} from "@pureadmin/utils";

export function useStaff(tableRef: Ref, treeRef: Ref) {
  const { t } = useI18n();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const roleOptions = ref([]);
  const choicesDict = ref({});
  const ruleFormRef = ref();
  // 上传头像信息
  const avatarInfo = ref();
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();

  const api = reactive({
    list: staffApi.list,
    fields: staffApi.fields,
    save: staffApi.save,
    delete: staffApi.delete
  });

  const auth = reactive({
    list: true,
    create: hasAuth("add"),
    update: hasAuth("edit"),
    delete: hasAuth("delete"),
    batchDelete: hasAuth("delete"),
    import: hasAuth("import"),
    export: hasAuth("export"),
    download: hasAuth("download")
  });
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      align: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "编号",
      prop: "id",
      width: 90
    },
    {
      label: "头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatar || userAvatar}
          preview-src-list={Array.of(row.avatar || userAvatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "姓名",
      prop: "username",
      minWidth: 130
    },
    {
      label: "昵称",
      prop: "nickname",
      minWidth: 130
    },
    {
      label: "性别",
      prop: "sex",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.sex === 1 ? "danger" : null}
          effect="plain"
        >
          {row.sex === 1 ? "女" : "男"}
        </el-tag>
      )
    },
    {
      label: "部门",
      prop: "dept.name",
      minWidth: 90
    },
    {
      label: "手机号码",
      prop: "phone",
      minWidth: 90,
      formatter: ({ phone }) => hideTextAtIndex(phone, { start: 3, end: 6 })
    },
    {
      label: "邮箱",
      prop: "email",
      minWidth: 120
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="激活"
          inactive-text="禁用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "禁用" : "激活"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        if (!hasAuth("edit")) {
          message("权限不足！", { type: "error" });
          return false;
        }
        api.save({ id: row.id, status: row.status }).then(res => {
          if (res.code == 200) {
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: true
              }
            );
            setTimeout(() => {
              switchLoadMap.value[index] = Object.assign(
                {},
                switchLoadMap.value[index],
                {
                  loading: false
                }
              );
              message("已成功修改用户状态", {
                type: "success"
              });
            }, 300);
          } else {
            message(res.error, { type: "error" });
          }
        });
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    treeRef.value.onTreeReset();
  };

  function onTreeSelect({ pk, selected }) {
    tableRef.value.searchFields.dept_id = selected ? pk : "";
    tableRef.value.onSearch();
  }

  const editForm = shallowRef({
    title: t("staff.title"),
    row: {
      status: row => {
        return row?.status ?? true;
      },
      sex: row => {
        return row?.sex ?? 0;
      },
      role_ids: row => {
        return row?.role_ids ?? [];
      },
      dept_id: row => {
        return row?.dept_id ?? "";
      }
    },
    formProps: {
      labelWidth: "100px",
      rules: {
        username: [
          {
            required: true,
            message: t("staff.username"),
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error(t("login.passwordReg")));
              } else if (!REGEXP_PWD.test(value)) {
                callback(new Error(t("login.passwordRuleReg")));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        nickname: [
          {
            required: true,
            message: t("staff.nickname"),
            trigger: "blur"
          }
        ],
        sex: [
          {
            required: true,
            message: t("staff.sex"),
            trigger: "blur"
          }
        ],
        dept_id: [
          {
            required: true,
            message: t("staff.dept_id"),
            trigger: "blur"
          }
        ],
        status: [
          {
            required: true,
            message: t("staff.status"),
            trigger: "blur"
          }
        ],
        phone: [
          {
            validator: (rule, value, callback) => {
              if (value === "" || !value) {
                callback();
              } else if (!isPhone(value)) {
                callback(new Error(t("login.phoneCorrectReg")));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (value === "" || !value) {
                callback();
              } else if (!isEmail(value)) {
                callback(new Error(t("login.emailCorrectReg")));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    },
    columns: ({ isAdd }) => {
      return [
        {
          prop: "username",
          valueType: "input",
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 }
        },
        {
          prop: "nickname",
          valueType: "input",
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 }
        },
        {
          prop: "sex",
          valueType: "select",
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 },
          // options: formatOptions(choicesDict.value["sex"])
          options: [
            { label: "男", value: 0 },
            { label: "女", value: 1 }
          ]
        },
        {
          prop: "password",
          valueType: "input",
          hideInForm: !isAdd,
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 }
        },
        {
          prop: "dept_id",
          valueType: "cascader",
          fieldProps: {
            props: {
              value: "id",
              label: "name",
              emitPath: false,
              checkStrictly: true
            }
          },
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 },
          options: formatHigherDeptOptions(cloneDeep(treeData.value))
        },
        {
          prop: "phone",
          valueType: "input",
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 }
        },
        {
          prop: "status",
          valueType: "radio",
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 },
          renderField: renderOption()
        },
        {
          prop: "email",
          valueType: "input",
          colProps: { xs: 24, sm: 24, md: 24, lg: 12, xl: 12 }
        },
        {
          prop: "role_ids",
          valueType: "select",
          fieldProps: {
            multiple: true
          },
          options: customRolePermissionOptions(roleOptions.value ?? [])
        },
        {
          prop: "remark",
          valueType: "textarea"
        }
      ];
    }
  });

  const cropRef = ref();
  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(ReCropperPreview, {
          ref: cropRef,
          imgSrc: row.avatar || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: done => {
        console.log("裁剪后的图片信息：", avatarInfo.value);
        // 根据实际业务使用avatarInfo.value和row里的某些字段去调用上传头像接口即可
        done(); // 关闭弹框
        tableRef.value.onSearch(); // 刷新表格数据
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(valid => {
          if (valid) {
            // 根据实际业务使用pwdForm.newPwd和row里的某些字段去调用重置用户密码接口即可
            api.save({ id: row.id, password: pwdForm.newPwd }).then(res => {
              if (res.code == 200) {
                // 表单规则校验通过
                message(`已成功重置 ${row.username} 用户的密码`, {
                  type: "success"
                });
                done(); // 关闭弹框
                tableRef.value.onSearch(); // 刷新表格数据
              } else {
                message(res.error, { type: "error" });
              }
            });
          }
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row) {
    // 选中的角色列表
    const ids = row.role_ids ?? [];
    addDialog({
      title: `分配 ${row.username} 用户的角色`,
      props: {
        formInline: {
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          ids,
          staff_id: row?.id ?? 0
        }
      },
      width: "400px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline as RoleFormItemProps;
        // 根据实际业务使用curData.ids和row里的某些字段去调用修改角色接口即可
        api.save({ id: row.id, role_ids: curData.ids }).then(res => {
          if (res.code == 200) {
            message(`用户 ${row.username} 的角色分配成功`, { type: "success" });
            done(); // 关闭弹框
            tableRef.value.onSearch(); // 刷新表格数据
          } else {
            message(res.error, { type: "error" });
          }
        });
      }
    });
  }

  onMounted(async () => {
    treeLoading.value = true;

    // 归属部门
    const { data } = await getDeptList({ page_type: 0 });
    treeData.value = handleTree(data.list, "id", "pid");
    treeLoading.value = false;

    // 角色列表
    roleOptions.value = (await getRoleList()).data.list;
  });

  return {
    api,
    auth,
    columns,
    deviceDetection,
    treeLoading,
    treeData,
    resetForm,
    onTreeSelect,
    editForm,
    buttonClass,
    handleUpload,
    handleReset,
    handleRole
  };
}
